package com.linln.admin.pcs.controller;


import com.linln.admin.config.IDCardEncryptor;
import com.linln.admin.pcs.service.NotificationMiddleService;
import com.linln.admin.pcs.service.VerifyLogService;
import com.linln.admin.system.service.AppService;
import com.linln.common.data.QuerySpec;
import com.linln.common.utils.*;
import com.linln.component.actionLog.annotation.EntityParam;
import com.linln.component.shiro.ShiroUtil;
import com.linln.modules.system.domain.*;
import com.linln.modules.system.repository.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.persistence.criteria.Predicate;
import javax.servlet.http.HttpServletRequest;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 护工护理权限管理
 */
@Controller
@RequestMapping("/pcs/porter/permission")
public class PorterPermissionController {

    @Autowired
    private AppService appService;
    @Autowired
    private PorterRepository porterRepository;
    @Autowired
    private PorterPermissionRepository porterPermissionRepository;
    @Autowired
    private DepRepository depRepository;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;
    @Autowired
    private VerifyLogRepository verifyLogRepository;
    @Autowired
    private VerifyLogService verifyLogService;
    @Autowired
    private NotificationMiddleService notificationMiddleService;
    @Autowired
    private UserRepository userRepository;


    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("pcs:porterPermission:index")
    public ResponseEntity<?> index(Model model, @EntityParam Porter porter) throws Exception {

        return appService.layTable(porterRepository, before -> {

                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("name", QuerySpec.LIKE)
                            .withMatcher("sex", QuerySpec.EQUAL)
                            .withMatcher("status", QuerySpec.EQUAL)
                            .withMatcher("phone", QuerySpec.LIKE);


                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("2")) {
                        Long companyId = user.getCompanyId();
                        querySpec.withMatcherValue("companyId", QuerySpec.EQUAL,companyId.toString());
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/porter_permission/index",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {
                        // 对每一项数据进行处理
                        Porter data = (Porter) item;

                        try {
                            //data.setAge(HelperUtil.getAge( IDCardEncryptor.aesDecrypt(data.getCardNo())));
                            data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(data.getPhone()));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }

                        QuerySpec querySpec = QuerySpec.matching();
                        querySpec.withMatcherValue("porterId", QuerySpec.EQUAL,data.getId().toString())
                                .withMatcherValue("verifyStatus", QuerySpec.NOT_EQUAL,"2")
                                .withMatcherValue("verifyStatus", QuerySpec.NOT_EQUAL,"3");
                        List<PorterPermission> porterPermissions = porterPermissionRepository.findAll(QuerySpec.of(querySpec));
                        data.setPorterPermissions(porterPermissions);
                    });
                }

        );

    }



    /**
     * 权限申请
     */
    @RequestMapping("/form")
    @RequiresPermissions("pcs:porterPermission:add")
    public String form(Model model, @EntityParam String ids) throws Exception {
        model.addAttribute("ids", ids);
        // 将字符串 ids 按逗号分割并转换为 Long 类型的列表
        List<Long> porterIds = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        Specification specification = (Specification<Porter>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, root.get("id").in(porterIds));
            return predicate;
        };
        List<Porter> porterList = porterRepository.findAll(specification);
        porterList.forEach(item -> {
            try {
                item.setAge(HelperUtil.getAge(IDCardEncryptor.aesDecrypt(item.getCardNo())));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }


            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherValue("porterId", QuerySpec.EQUAL,item.getId().toString())
                    .withMatcherValue("verifyStatus", QuerySpec.NOT_EQUAL,"2")
                    .withMatcherValue("verifyStatus", QuerySpec.NOT_EQUAL,"3");
            List<PorterPermission> porterPermissions = porterPermissionRepository.findAll(QuerySpec.of(querySpec));
            item.setPorterPermissions(porterPermissions);
        });
        List<String> porterDepIds = new ArrayList<>();
        if(porterList.size()==1){
            //如果只是一个护工则复选该护工已通过的权限
            List<PorterPermission> porterPermissions = porterList.get(0).getPorterPermissions();
            porterDepIds = porterPermissions.stream()
                    .map(PorterPermission::getDepId)
                    .collect(Collectors.toList());

        }
        model.addAttribute("porterDepIds", porterDepIds);
        model.addAttribute("porterList", porterList);
        List<Dep> depList = depRepository.findAll();
        model.addAttribute("depList", depList);
        return "/pcs/porter_permission/form";

    }



    /**
     * 保存权限
     * @param model
     * @return
     * @throws Exception
     */
    @PostMapping("/save")
    @RequiresPermissions("pcs:porterPermission:add")
    public ResponseEntity<?> save (Model model, @RequestParam String ids, @RequestParam("dep[]") List<String> depIds, HttpServletRequest request) throws Exception {
        // 将字符串 ids 按逗号分割并转换为 Long 类型的列表
        List<Long> porterIds = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        Specification specification = (Specification<PorterPermission>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, root.get("porterId").in(porterIds));
            // 查询审核状态为0,1的
            List<Byte> statusList = new ArrayList<>();
            statusList.add((byte) 0);
            statusList.add((byte) 1);
            predicate = cb.and(predicate, root.get("verifyStatus").in(statusList));
            return predicate;
        };
        //根据porterId删除旧的权限
//        List<PorterPermission> porterPermissions = porterPermissionRepository.findAll(specification);
//        porterPermissions.forEach(item -> {
//            porterPermissionRepository.delete(item);
//        });

        //循环选择的depId查出对应的name
        List<Dep> depList = new ArrayList<>();
        for (int i = 0; i < depIds.size(); i++) {
            QuerySpec querySpec = QuerySpec.matching();
            querySpec.withMatcherValue("deptId", QuerySpec.EQUAL,depIds.get(i));
            depList.add(depRepository.findAll(QuerySpec.of(querySpec), Sort.by(Sort.Direction.DESC, "id")).get(0));
//            Dep dep = depRepository.findById(depIds.get(i)).get();
//            depList.add(dep);
        }


        Specification specification1 = (Specification<Porter>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, root.get("id").in(porterIds));
            return predicate;
        };
        List<Porter> porterList = porterRepository.findAll(specification1);

        porterList.forEach(item -> {
            depList.forEach(item1 -> {
                //查询该护工是否存在该权限的状态为非取消及非驳回的
                QuerySpec querySpec = QuerySpec.matching();
                querySpec.withMatcherValue("porterId", QuerySpec.EQUAL, String.valueOf(item.getId()))
                        .withMatcherValue("depId", QuerySpec.EQUAL,item1.getDeptId())
                        .withMatcherValue("verifyStatus", QuerySpec.NOT_EQUAL,"2")
                        .withMatcherValue("verifyStatus", QuerySpec.NOT_EQUAL,"3");
                if (porterPermissionRepository.findAll(QuerySpec.of(querySpec)).size()==0){
                    PorterPermission porterPermission = new PorterPermission();
                    porterPermission.setPorterId(item.getId());
                    porterPermission.setCompanyId(item.getCompanyId());
                    porterPermission.setPorterName(item.getName());
                    porterPermission.setDepId(item1.getDeptId());
                    porterPermission.setDepName(item1.getName());
                    porterPermission.setVerifyStatus(0);
                    porterPermission.setCompanyName(item.getCompanyName());
                    porterPermission.setStatus((byte) 1);
                    porterPermission.setCanalStatus(0);
                    porterPermissionRepository.save(porterPermission);

                    //推送事项到中台
                    QuerySpec querySpecUser = QuerySpec.matching();
                    querySpecUser.withMatcherValue("depId", QuerySpec.EQUAL,porterPermission.getDepId());
                    List<User> userList = userRepository.findAll(QuerySpec.of(querySpecUser));
                    String content = "您有新的申请【护工（"+porterPermission.getPorterName()+"）申请了陪护权限】，请及时处理";
                    userList.forEach(user -> {
                        notificationMiddleService.send(content,  "/pcs/porter/permission/examine?verifyStatus=0", user.getMiddleUserId(), request);
                    });

                }
            });
        });

        return ResponseEntity.ok(ResultVoUtil.success("成功"));

    }


    /**
     * 申请记录
     */
    @GetMapping("/log")
    @RequiresPermissions("pcs:porterPermission:log")
    public String log(@RequestParam Long id, Model model){
        Specification specification = (Specification<PorterPermission>) (root, query, cb) -> {
            Predicate predicate = cb.conjunction();  // 初始条件
            // 使用in查询
            predicate = cb.and(predicate, cb.equal(root.get("porterId"),id));
            return predicate;
        };
        QuerySpec querySpec = QuerySpec.matching();
        querySpec.withMatcherValue("porterId", QuerySpec.EQUAL, String.valueOf(id));
        List<PorterPermission> log = porterPermissionRepository.findAll(QuerySpec.of(querySpec), Sort.by(Sort.Direction.DESC, "id"));
        log.forEach(item -> {
            item.setCreateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", item.getCreateTime()));
        });

        model.addAttribute("log", log);

        return "/pcs/porter_permission/log";
    }




    /**
     * 权限审核
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/verify")
//    @RequiresPermissions("pcs:porterPermission:verify")
    public ResponseEntity<?> verify(Model model) throws Exception {

        String ids = HttpServletUtil.getParameter("ids");
        Integer verifyStatus = HttpServletUtil.getParameterInt("verifyStatus");
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim)
                .map(Long::parseLong)
                .collect(Collectors.toList());
        idList.forEach(item -> {
            PorterPermission porterPermission = porterPermissionRepository.getById(item);
            porterPermission.setVerifyStatus(verifyStatus);
            if(verifyStatus==3){
                porterPermission.setCanalStatus(1);
                porterPermission.setVerifyStatus(1);
            }

            if(verifyStatus==4){
                //取消通过
                porterPermission.setCanalStatus(2);
                porterPermission.setVerifyStatus(3);
            }

            if(verifyStatus==5){
                //取消驳回
                porterPermission.setCanalStatus(3);
                porterPermission.setVerifyStatus(1);

            }

            verifyLogService.setVerifyLog(item, verifyStatus,1,"");
            porterPermissionRepository.save(porterPermission);
        });
        return ResponseEntity.ok(ResultVoUtil.success("成功"));

    }



    /**
     * 服务权限管理列表页面(护士长)
     */
    @GetMapping("/examine")
    @RequiresPermissions("pcs:porterPermission:examine")
    public ResponseEntity<?> examine(Model model, @EntityParam PorterPermission porterPermission) {

        return appService.layTable(porterPermissionRepository, before -> {
                    model.addAttribute("verifyStatus", HttpServletUtil.getParameter("verifyStatus",""));
                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("porterName", QuerySpec.LIKE)
                            .withMatcher("companyName", QuerySpec.LIKE)
                            .withMatcher("verifyStatus", QuerySpec.EQUAL)
                            .withMatcher("canalStatus", QuerySpec.EQUAL)
                            .withMatcherValue("status", QuerySpec.EQUAL,"1");


                    User user = ShiroUtil.getSubject();
                    if (user.getType()!=null&&user.getType().equals("1")) {
                        String depId = user.getDepId();
                        querySpec.withMatcherValue("depId", QuerySpec.EQUAL,depId);
                    }
                    return QuerySpec.of(querySpec);
                },

                "/pcs/porter_permission/index_examine",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
                    pageResult.getContent().forEach(item -> {
                        // 对每一项数据进行处理
                        PorterPermission data = (PorterPermission) item;
                        porterRepository.findById(data.getPorterId()).ifPresent(porter -> {
                            data.setSex(porter.getSex());
                            data.setAge(porter.getAge());
                            try {
                                data.setPhone(IDCardEncryptor.aesTuoMinPhoneDecrypt(porter.getPhone()));
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }

                        });
                    });
                }

        );

    }

    //权限审核(护士长)
    @RequestMapping("/canal")
//    @RequiresPermissions("pcs:porterPermission:verify")
    public ResponseEntity<?> canal(Model model, @EntityParam PorterPermission porterPermission,HttpServletRequest request) {
        String method = HttpServletUtil.getMethod();
        if (method.equals("GET")) {
            String id = HttpServletUtil.getParameter("id");
            Integer verifyStatus = HttpServletUtil.getParameterInt("verifyStatus");
            model.addAttribute("id", id);
            model.addAttribute("verifyStatus", verifyStatus);
            // 必须手动渲染模板
            Context context = new Context();
            // 将数据加入到 Thymeleaf 上下文中
            context.setVariables(model.asMap());
            // 使用 Thymeleaf 渲染模板
            StringWriter writer = new StringWriter();
            thymeleafViewResolver.getTemplateEngine().process("/pcs/porter_permission/verify", context, writer);

            return ResponseEntity.ok( writer.toString());
        }else{
            PorterPermission porterPermission1 = porterPermissionRepository.getById(porterPermission.getId());
            String remark = "";
            if(porterPermission.getCanalRemark()!=null){
                //权限取消申请
                remark = porterPermission.getCanalRemark();
                User user = ShiroUtil.getSubject();
                porterPermission1.setCanalName(user.getNickname());
                porterPermission1.setCanalRemark(porterPermission.getCanalRemark());
                porterPermission1.setCanalTime(HelperUtil.dateFormat(new Date(),"yyyy-MM-dd HH:mm:ss"));
            }
            if(porterPermission.getRemark()!=null){
                //驳回权限申请
                remark = porterPermission.getRemark();
                porterPermission1.setRemark(porterPermission.getRemark());
            }
            if(porterPermission.getCanalBRemark()!=null){
                //驳回权限取消申请
                remark = porterPermission.getCanalBRemark();
                porterPermission1.setCanalBRemark(porterPermission.getCanalBRemark());
            }
            Integer verifyStatus = porterPermission.getVerifyStatus();
            porterPermission1.setVerifyStatus(verifyStatus);
            if(verifyStatus==3){
                //权限取消申请
                porterPermission1.setCanalStatus(1);
                porterPermission1.setVerifyStatus(1);
            }
            if(verifyStatus==5){
                //取消驳回
                porterPermission1.setCanalStatus(3);
                porterPermission1.setVerifyStatus(1);

            }

            verifyLogService.setVerifyLog(porterPermission.getId(), porterPermission.getVerifyStatus(),1,remark);
            porterPermissionRepository.save(porterPermission1);
            if(verifyStatus==3){
                //发起权限取消申请,将数据推送到中台
                String content = "您有一个新的取消服务权限的申请【护工（"+porterPermission1.getPorterName()+"）的"+porterPermission1.getDepName()+"陪护权限】，请及时处理";
                QuerySpec querySpecUser = QuerySpec.matching();
                querySpecUser.withMatcherValue("type", QuerySpec.EQUAL, "0");
                List<User> userList = userRepository.findAll(QuerySpec.of(querySpecUser));
                userList.forEach(user -> {
                    notificationMiddleService.send(content,  "/pcs/porter/permission/canallist?canalStatus=1", user.getMiddleUserId(), request);
                });
            }
            return ResponseEntity.ok(ResultVoUtil.success("成功"));
        }

    }




    /**
     * 取消服务权限审核列表页面(医院)
     */
    @GetMapping("/canallist")
    @RequiresPermissions("pcs:porterPermission:canallist")
    public ResponseEntity<?> canallist(Model model, @EntityParam PorterPermission porterPermission) {

        return appService.layTable(porterPermissionRepository, before -> {

                    // 添加模板变量
                    return model;

                },

                after -> {
                    QuerySpec querySpec = QuerySpec.matching();
                    querySpec.withMatcher("porterName", QuerySpec.LIKE)
                            .withMatcher("companyName", QuerySpec.LIKE)
                            .withMatcherValue("status", QuerySpec.EQUAL,"1");

                    Integer canalStatus = HttpServletUtil.getParameterInt("canalStatus",0);
                    if(canalStatus != 0){
                        querySpec.withMatcherValue("canalStatus", QuerySpec.EQUAL, String.valueOf(canalStatus));
                    }else{
                        querySpec.withMatcherValue("canalStatus", QuerySpec.NOT_EQUAL, String.valueOf(0));
                    }
//                    List<Object> verifyStatusList = new ArrayList<>();
//                    verifyStatusList.add(1);
//                    verifyStatusList.add(2);
//                    verifyStatusList.add(3);
//                    querySpec.withMatcherIn("canalStatus", verifyStatusList);
                    return QuerySpec.of(querySpec);
                },

                "/pcs/porter_permission/canallist",

                (pageResult) -> {
                    // 在这里处理 pageResult
                    // 例如：修改每一条数据
//                    pageResult.getContent().forEach(item -> {
//                        // 对每一项数据进行处理
//                        PorterPermission data = (PorterPermission) item;
//                        Porter porter = porterRepository.getById(data.getPorterId());
//                        if(porter!=null){
//                            data.setSex(porter.getSex());
//                            data.setPhone(porter.getPhone());
//                            data.setAge(HelperUtil.getAge(porter.getCardNo()));
//                        }
//                    });
                }

        );

    }



}
